/**
 * Created by user on 2015/9/18.
 */

angular.module('mis.bannerManager.controllers', [])
    .controller('bannerCtrl', ['$scope','$http', '$location', function ($scope, $http, $location) {

        //var larSelect = new gObj.larSelect();
        //larSelect.paint($(".ral-list-choice"));
        $scope.currentPage = 1;
        $scope.pageSize = 15;

        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/banner/bannerList/:page/:size',
            ajax: $http,
            success:function(data){
                data.data.list.forEach(function(temp) {

                    temp.imageURL = 'http://'+ imgHost+ temp.imageURL;
                });

                $scope.resultList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
            },
            error: function(err){
                //$scope.communityList = null;
            },
            params: {}
        });

        //全选列表
        $scope.allSelected = function () {
            $scope.pagination.allSelected();
        };

        //级联框
        var cascadData = {
            provinceUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionPrivince',
            cityUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCity',
            cityAreaUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCounty',
            villageUrl: 'http://' + backOfficeHost + '/rest/v1.0/mis/community/communityList',
            ajax: $http
        };
        $scope.cascading = new gObj.cascading(cascadData);
        $scope.cascading.paint($(".city-cascading")[0],false, 'list');

        $scope.selectFile = function (files,model) {
            if (model == 'add') {
                document.getElementById("image_result").innerHTML = '';
            }else{
                document.getElementById("image_result_edit").innerHTML = '';
            }
            showImages(model);
        };

        var reader = null;
        if (FileReader) {
            reader = new FileReader();
        } else {
            alert("浏览器暂时不支持FileReader");
        }
        var fileList = {}, length = 0, length1 = 0;
        var showImages = function (model) {

            if(model =='add'){
                var imageEle  = document.getElementById("images_upload");
            }else{
                var imageEle  = document.getElementById("images_upload_edit");
            }

            //获取上传的多个文件
            fileList = imageEle.files;
            length = fileList.length;
            length1 = fileList.length;

            //获取文件信息
            readURL(model);
        };

        var readURL = function (model) {

            reader.readAsDataURL(fileList[length1 - length]);
            reader.onload = function () {
                var img = document.createElement("img");
                img.src = reader.result;
                img.width = 200;
                if(model =='add') {
                    document.getElementById("image_result").appendChild(img);
                }else{
                    document.getElementById("image_result_edit").appendChild(img);
                }
                length--
                if (length == 0)return;
                readURL(model);
            };
        };

        //过滤小区
        $scope.cnameFilter = function(name,model){

            if(!name){
                return;
            }
            else {
                if (name.length < 2 && name.length > 0) {
                    return;
                }
            };

            var html = "";
            var countyId = null;
            var cname = null;
            if (model == 'add') {
                countyId = $('#county_list')[0].dataset.cId;
                cname = $scope.cname;
            }else{
                countyId = $('#county_edit')[0].dataset.cId;
                cname = $scope.cname_edit;
            }

            var opt = {
                countyId: countyId,
                communityName: cname,
                isValid: true
            };
            console.debug(opt);
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/community/communityList', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                console.debug(data);
                if (model == 'add') {
                    $scope.communityList = data.data.list;
                    $(document).on("dblclick","#communities_select option",function(){
                        $(this).appendTo('#selCommunitys');
                    });
                    $(document).on("dblclick","#selCommunitys option",function(){
                        $(this).appendTo('#communities_select');
                    });

                }else{
                    $scope.communityList_edit = data.data.list;
                    $(document).on("dblclick","#communities_select_edit option",function(){
                        $(this).appendTo('#selCommunitys_edit');
                    });
                    $(document).on("dblclick","#selCommunitys_edit option",function(){
                        $(this).appendTo('#communities_select_edit');
                    });
                }



            }).error(function () {
            });

        };


        //全部移到右边
        $scope.addAllCommunity = function (model) {

            if(model =='add') {
                //获取全部的选项,删除并追加给对方
                $('#communities_select option').appendTo('#selCommunitys');
            }else{
                //获取全部的选项,删除并追加给对方
                $('#communities_select option').appendTo('#selCommunitys_edit');
            }
            $scope.commList = [];
        };

        //全部移到左边
        $scope.removeAllCommunity = function (model) {

            if(model =='add') {

                var selectedCom = $('#selCommunitys option');
                for (var i = 0; i < selectedCom.length; i++) {
                    var item = {objId: selectedCom[i].value, communityName: selectedCom[i].label};
                    $scope.commList.push(item);
                }

                $('#selCommunitys option').appendTo('#communities_select');
            }else{

                var selectedCom = $('#selCommunitys_edit option');
                for (var i = 0; i < selectedCom.length; i++) {
                    var item = {objId: selectedCom[i].value, communityName: selectedCom[i].label};
                    $scope.commList.push(item);
                }

                $('#selCommunitys option').appendTo('#communities_select_edit');

            }
        };
        //移到右边
        $scope.addCommunity = function (model) {

            if(model =='add') {
                var selectedCom = $('#communities_select option:selected');
                for (var i = 0; i < selectedCom.length; i++) {
                    for (var j in $scope.commList) {
                        if (selectedCom[i].value == $scope.commList[j].objId)$scope.commList.splice(j, 1);
                    }
                }
                //先判断是否有选中
                if (!$("#communities_select option").is(":selected")) {
                    alert("请选择需要移动的选项")
                }
                //获取选中的选项，删除并追加给对方
                else {
                    $('#communities_select option:selected').appendTo('#selCommunitys');
                }
            }else{

                var selectedCom = $('#communities_select_edit option:selected');
                for (var i = 0; i < selectedCom.length; i++) {
                    for (var j in $scope.commList) {
                        if (selectedCom[i].value == $scope.commList[j].objId)$scope.commList.splice(j, 1);
                    }
                }
                //先判断是否有选中
                if (!$("#communities_select_edit option").is(":selected")) {
                    alert("请选择需要移动的选项")
                }
                //获取选中的选项，删除并追加给对方
                else {
                    $('#communities_select_edit option:selected').appendTo('#selCommunitys_edit');
                }
            };
        };

        //移到左边
        $scope.removeCommunity = function (model) {

            if(model =='add') {
                var selectedCom = $('#selCommunitys option:selected');
                for (var i = 0; i < selectedCom.length; i++) {
                    var item = {objId: selectedCom[i].value, communityName: selectedCom[i].label};
                    $scope.commList.push(item);
                }
                //先判断是否有选中
                if (!$("#selCommunitys option").is(":selected")) {
                    alert("请选择需要移动的选项")
                }
                else {
                    $('#selCommunitys option:selected').appendTo('#communities_select');
                }
            }else{

                var selectedCom = $('#selCommunitys_edit option:selected');
                for (var i = 0; i < selectedCom.length; i++) {
                    var item = {objId: selectedCom[i].value, communityName: selectedCom[i].label};
                    $scope.commList.push(item);
                }
                //先判断是否有选中
                if (!$("#selCommunitys_edit option").is(":selected")) {
                    alert("请选择需要移动的选项")
                }
                else {
                    $('#selCommunitys_edit option:selected').appendTo('#communities_select_edit');
                }

            }
        };


        //新增
        $scope.add = function(addData, temp){
            var target = temp.target;

            if(!addData){alert('请填写数据!');return;};
            if(!addData.bannerType){alert('请选择Banner类别!');return;};
            if(!addData.openType){alert('请选择打开方式!');return;};
            if(!addData.beginDate){alert('请选择开始日期!');return;};
            if(!addData.endDate){alert('请选择结束日期!');return;};


            if(addData.bannerType == 2 && !addData.url){
                alert('集市Banner必须配置URL!');
                return;
            };

            var opt = {
                name : addData.bannerName
                ,type:addData.bannerType
                ,url: addData.url
                ,beginDate : addData.beginDate
                ,endDate : addData.endDate
                ,openType : addData.openType
                ,bannerOrder : addData.bannerOrder
            };

            var provinceId = $scope.cascading.getProvince (target);
            var cityId = $scope.cascading.getCity (target);
            var countyId = $scope.cascading.getCityArea (target);
            //var city = $scope.cascading.getCityVal (target);
            //selectMenu.menu=$('#selCommunitys');
            var community = $('#selCommunitys').val();

            //if(provinceId && !cityId){
            //    alert('请选择城市!');
            //    return;
            //};

            var level = 0;
            if (provinceId) {
                opt.provinceId = provinceId;
                level = 1;
            };
            if (cityId) {
                opt.cityId = cityId;
                level = 2;
            };
            if (countyId) {
                opt.countyId = countyId;
                level = 3;
            }
            if (community){
                opt.community = community;
                level = 4;
            }
            opt['level']= level;

            //var contentId;
            //var openType = 3;
            ////获取url第一个参数
            //if(addData.url) {
            //    var parames = getQueryParames(addData.url);
            //    if (!$.isEmptyObject(parames)) {
            //        var index = 0;
            //        for (key in parames) {
            //            if (index == 0){
            //                contentId = parames[key];
            //                if(key =='topicId'){
            //                    openType = 4
            //                }
            //            }
            //            index++;
            //        };
            //    };
            //};
            //opt.contentId = contentId;
            //opt.openType = openType;

            if( addData.bannerType ==2 &&  addData.openType==4){
                alert('集市Banner不能设置专题!');
                return;
            };

            var fd = new FormData();
            if (fileList != null) {
                for (var i = 0; i < fileList.length; i++) {
                    var index = i + 1;
                    fd.append('image' + index, fileList[i]);
                }
            };

            if (fileList.length>0) {
                if(fileList.length>1){
                    alert('上传图片不能超过6张!');
                    return;
                };
                //上传图片
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {
                    opt.imageURL= images.data[0];
                    $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/banner/bannerAdd', opt, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        $scope.addData = {};
                        $scope.commList =  [];
                        $scope.pagination.selectPage(1);//插入成功显示第一页
                        $('#doc-modal-add').modal("close");
                        alert("添加Banner成功");

                    }).error(function (err) {
                        alert(err);
                    });

                });

            }else{

                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/banner/bannerAdd', opt, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.addData = {};
                    $scope.commList =  [];
                    $scope.pagination.selectPage(1);//插入成功显示第一页
                    $('#doc-modal-add').modal("close");
                    alert("添加Banner成功");

                }).error(function (err) {
                    alert(err);
                });
            };

        };

        //删除
        $scope.delete = function(){
            var params = {
                url: 'http://' + backOfficeHost + '/rest/v1.0/mis/banner/bannerDelete',
                checkObj: $(".item-check"),//checkbox对象
                key: "bannerID",
                success: function(data){
                    var number = $(".am-active").text();//当前页码
                    $scope.pagination.selectPage(number);
                    alert("删除成功！");
                    //$scope.menuUpdate(data);
                },
                error: function(){}
            };
            $scope.pagination.listDelete(params);
        };

        $scope.updateData = {};
        //编辑
        $scope.bannerEdit = function(banner){

            //$scope.updateData = banner;
            //$scope.url = banner.url;
            //$scope.image = null;
            fileList = {};
            $scope.cascading.paint($("#cascad-edit")[0],false, 'edit');
            console.debug(banner);
            //document.getElementById('begin').value  = (new Date(banner.beginDate)).format('yyyy-MM-dd');
            //document.getElementById('end').value  = (new Date(banner.endDate)).format('yyyy-MM-dd');
            //$scope.updateData.beginDate = banner.beginDate;
            //$scope.updateData.endDate = banner.endDate;
            banner.beginDate = (new Date(banner.beginDate)).format('yyyy-MM-dd hh:mm');
            banner.endDate = (new Date(banner.endDate)).format('yyyy-MM-dd hh:mm');
            $scope.updateDate = banner;

            //$scope.cascading.paint($("#cascad-edit")[0],false);
            if(banner.province) {
                $("#cascad-edit").find(".c-provinces").val(banner.province.name);
                if (banner.province)$("#cascad-edit").find(".c-provinces")[0].dataset.cId = banner.province.objId;
            };
            if(banner.city) {
                $("#cascad-edit").find(".c-citys").val(banner.city.name);
                if (banner.city)$("#cascad-edit").find(".c-citys")[0].dataset.cId = banner.city.objId;
            };
            if(banner.county) {
                $("#cascad-edit").find(".c-cityArea").val(banner.county.name);
                if (banner.county)$("#cascad-edit").find(".c-cityArea")[0].dataset.cId = banner.county.objId;
            };


            if(banner.community)$('#selCommunitys').val(banner.community);

            console.debug($scope.updateData);

            $('#doc-modal-edit').modal({target: '#doc-modal-edit', width: 800, height: 600});
        };

        $scope.update = function(updateData,temp){
            var target = temp.target;

            if(!updateData){alert('请填写数据!');return;};
            if(!updateData.type){alert('请选择Banner类别!');return;};
            if(!updateData.openType){alert('请选择打开方式!');return;};
            if(!updateData.beginDate){alert('请选择开始日期!');return;};
            if(!updateData.endDate){alert('请选择结束日期!');return;};

            if(updateData.type == 2 && !updateData.url){
                alert('集市Banner必须配置URL!');
                return;
            };

            var uData = {bannerID:"",banner:{}};
            if(updateData.objId)uData.bannerID = updateData.objId;

            if(updateData.name != null)uData.banner.name = updateData.name;
            if(updateData.type != null)uData.banner.type = updateData.type;
            if(updateData.openType != null)uData.banner.openType = updateData.openType;
            if(updateData.bannerOrder != null)uData.banner.bannerOrder = updateData.bannerOrder;
            if(updateData.url != null)uData.banner.url = updateData.url;
            if(updateData.beginDate != null)uData.banner.beginDate = updateData.beginDate;
            if(updateData.endDate != null)uData.banner.endDate = updateData.endDate;

            var provinceId = $scope.cascading.getProvince (target);
            var cityId = $scope.cascading.getCity (target);
            var countyId = $scope.cascading.getCityArea (target);
            var community = $('#selCommunitys_edit').val();

            //if(provinceId && !cityId){
            //    alert('请选择城市!');
            //    return;
            //};

            if(community && community.length>1){
                alert('只能选择一个小区');
                return;
            }
            var level = 0;
            uData.banner.province = null;
            if (provinceId) {
                uData.banner.province = provinceId;
                level =1;
            };
            uData.banner.city = null;
            if (cityId) {
                uData.banner.city = cityId;
                level =2;
            };
            uData.banner.county = null;
            if (countyId) {
                uData.banner.county = countyId;
                level =3;
            };
            uData.banner.community = null;
            if(community){
                uData.banner.community = community[0];
                level =4;
            }
            uData.banner.level = level;

            //var contentId;
            //var openType = 3;
            ////获取url第一个参数
            //if(updateData.url) {
            //    var parames = getQueryParames(updateData.url);
            //    if (!$.isEmptyObject(parames)) {
            //        var index = 0;
            //        for (key in parames) {
            //            if (index == 0){
            //                contentId = parames[key];
            //                if(key =='topicId'){
            //                    openType = 4
            //                }
            //            }
            //            index++;
            //        };
            //    };
            //};
            //uData.banner.contentId = contentId;
            //uData.banner.openType = openType;

            if( updateData.type ==2 && updateData.openType==4){
                alert('集市Banner不能设置专题!');
                return;
            };

            var fd = new FormData();
            if (fileList != null) {
                for (var i = 0; i < fileList.length; i++) {
                    var index = i + 1;
                    fd.append('image' + index, fileList[i]);
                }
            };

            if(fileList.length>0){

                if(fileList.length>1){
                    alert('上传图片不能超过1张!');
                    return;
                };

                //上传图片
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {

                    uData.banner.imageURL = images.data[0];

                    var params = {
                        url: 'http://' + backOfficeHost + '/rest/v1.0/mis/banner/bannerEdit',
                        updateData: uData,
                        success: function (data) {
                            var pageNumber = $(".am-active").text();//当前页码
                            $('#doc-modal-edit').modal("close");
                            $('#image_result_edit').empty();
                            $scope.updateData = null;
                            $scope.pagination.selectPage(pageNumber);
                            if (data.result.status == 1) {
                                alert("修改成功！");
                            } else {
                                alert("修改失败！");
                            }
                        },
                        error: function () {
                            var number = $(".am-active").text();//当前页码
                            $('#doc-modal-edit').modal("close");
                            $('#image_result_edit').empty();
                            $scope.updateData = null;
                            alert("修改失败！");
                        }
                    };
                    $scope.pagination.listUpdate(params);

                });


            }else {

                var params = {
                    url: 'http://' + backOfficeHost + '/rest/v1.0/mis/banner/bannerEdit',
                    updateData: uData,
                    success: function(data){
                        var pageNumber = $(".am-active").text();//当前页码
                        $('#doc-modal-edit').modal("close");
                        $('#image_result_edit').empty();
                        $scope.updateData = null;
                        $scope.pagination.selectPage(pageNumber);
                        if(data.result.status == 1){
                            alert("修改成功！");
                        }else{
                            alert("修改失败！");
                        }
                    },
                    error: function(){
                        var number = $(".am-active").text();//当前页码
                        $('#doc-modal-edit').modal("close");
                        $('#image_result_edit').empty();
                        $scope.updateData = null;
                        alert("修改失败！");
                    }
                };
                $scope.pagination.listUpdate(params);

            };
        };


        //搜索
        $scope.search = function (temp) {
            var btn = temp.target;

            //var countyId = $scope.cascading.getCityArea(btn);
            //var desc = $scope.cascading.getVillage(btn);

            var opt = {};
            //if (countyId) body.countyId = countyId;
            if ($scope.bannerName) opt.name = $scope.bannerName;
            if ($scope.bannerType) opt.type = $scope.bannerType;
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/banner/bannerList/' + 1 + '/' + $scope.pageSize, opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                data.data.list.forEach(function(temp) {
                    temp.imageURL = 'http://'+ imgHost+ temp.imageURL;
                });
                $scope.resultList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;

                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $scope.pagination.searchParams = opt;
            }).error(function (err) {
                alert(err);
            });

        };


        $scope.bannerPushShow = function(banner){

            $scope.bannerPush = banner;
            $scope.pushMsg ='';

            if(!banner.name) {alert('Banner没有名称，无法推送！'); return};
            if(!banner.url &&(banner.openType==3 || banner.openType==4) ) {alert('Banner没有起关联url，无法推送！'); return};
            //if(!banner.url) {alert('Banner没有起关联url，无法推送！'); return};

            //if(!banner.level) {alert('Banner没有选择推送区域，无法推送！'); return};
            if(!banner.beginDate) {alert('Banner没有开始时间，无法推送！'); return};
            if(!banner.endDate) {alert('Banner没有结束时间，无法推送！'); return};

            console.debug($scope.bannerPush);
            $('#doc-modal-push').modal({target: '#doc-modal-push', width: 800, height: 360 });

        };

        $scope.bannerPushMsg = function(msg){

            if(!$scope.pushMsg){
                alert('请填写推送内容!');
                $('#loading').modal("close");
                return;
            };

            var pushCommunity ={};

            if($scope.bannerPush.province) pushCommunity.provinceId = $scope.bannerPush.province.objId;
            if($scope.bannerPush.city) pushCommunity.cityId = $scope.bannerPush.city.objId;
            if($scope.bannerPush.county) pushCommunity.countyId = $scope.bannerPush.county.objId;
            if($scope.bannerPush.community) pushCommunity._id = $scope.bannerPush.community.objId;

            var contentId;
            if($scope.bannerPush.openType ==3)
            {
                contentId = getQueryString($scope.bannerPush.url,'activityId');
            }
            else if($scope.bannerPush.openType==4){
                contentId = getQueryString($scope.bannerPush.url,'topicId');
            };

            //if($scope.bannerPush.url){
            //    contentId = getQueryString($scope.bannerPush.url,'activityId');
            //    if(!contentId){
            //        contentId = getQueryString($scope.bannerPush.url,'topicId');
            //    }
            //};

            var opt = {
                level:$scope.bannerPush.level,
                //tag: '活动',
                url: $scope.bannerPush.url,
                openType: $scope.bannerPush.openType,
                contentId: contentId,
                desc: msg,
                pushCommunity : pushCommunity

            };

            if($scope.bannerPush.level =='2'){
                opt.tags = [$scope.bannerPush.city.name];
            };

            console.debug(opt);
            $('#doc-modal-push').modal("close");

            $('#loading').modal({target: '#loading'});

            if(opt.url) {
                var parm = getQueryString(opt.url, 'topicId');
                if (parm) {
                    //$http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/shortUrl', {url: opt.url}, {
                    //    headers: {'Content-Type': 'application/json;charset=utf-8'}
                    //}).success(function (data) {
                    opt.url = opt.url.substr(0, opt.url.indexOf('?'));
                };
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/banner/bannerPush', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (data.result.status == 1) {
                    $('#loading').modal("close");
                    alert("banner推送完成！");
                } else {
                    $('#loading').modal("close");
                    alert("banner推送失败！");
                    //$scope.pagination.selectPage($scope.currentPage);
                }

            }).error(function (err) {
                $('#loading').modal("close");
                alert("banner推送失败！");
                //$scope.pagination.selectPage($scope.currentPage);
            });

                //}).error(function (err) {
                //    $('#loading').modal("close");
                //    alert("获取短连接失败！");
                //    //$scope.pagination.selectPage($scope.currentPage);
                //});

            //}else{

                //$http.post('http://' + backOfficeHost + '/rest/v1.0/mis/banner/bannerPush', opt, {
                //    headers: {'Content-Type': 'application/json;charset=utf-8'}
                //}).success(function (data) {
                //
                //    if (data.result.status == 1) {
                //        $('#loading').modal("close");
                //        alert("banner推送完成！");
                //    } else {
                //        $('#loading').modal("close");
                //        alert("banner推送失败！");
                //        //$scope.pagination.selectPage($scope.currentPage);
                //    }
                //
                //}).error(function (err) {
                //    $('#loading').modal("close");
                //    alert("banner推送失败！");
                //    //$scope.pagination.selectPage($scope.currentPage);
                //});

            //};



        };


    }]);
